<?php if (!defined('DB_PEREFIX')) exit;

$id = $_GET['id'];
$order = "block_pos";
if (isset($_GET['order'])) $order = $_GET['order'];

if ($_GET['delete'] == true && isset($_GET['id'])) {
	$b = @mysql_query ("SELECT * FROM ".DB_PEREFIX."_blocks WHERE block_id = '$id'");
	$blk = @mysql_fetch_array ($b);
	$block = $blk['block_pos'] + 1;
	$align = $blk['block_align'];
	$delete = @mysql_query ("DELETE FROM ".DB_PEREFIX."_blocks WHERE block_id = '$id'");
	while (@mysql_num_rows(mysql_query("SELECT * FROM ".DB_PEREFIX."_blocks WHERE block_pos = '$block' && block_align = '$align'")) == 1) {
		@mysql_query ("UPDATE ".DB_PEREFIX."_blocks SET block_pos = '".($block - 1)."' WHERE block_pos = '$block' && block_align = '$align'");
		$block++;
	}
	if ($delete) site_message ("Блок удален");
	else site_error ("Ошибка БД или нет такой записи");
}
if ($_GET['mod'] == "m_up" && isset($_GET['id'])) {
	$block = @mysql_fetch_array(mysql_query ("SELECT * FROM ".DB_PEREFIX."_blocks WHERE block_id = '$id'"));
	if ($block) {
		$its = $block['block_pos'];
		$prw = $block['block_pos'] - 1;
		$align = $block['block_align'];
		if (@mysql_num_rows(mysql_query("SELECT * FROM ".DB_PEREFIX."_blocks WHERE block_pos = '$prw' && block_align = '$align'")) == 1) {
			$up0 = @mysql_query ("UPDATE ".DB_PEREFIX."_blocks SET block_pos = '$its + 1000' WHERE block_pos = '$prw' && block_align = '$align'");
			$up = @mysql_query ("UPDATE ".DB_PEREFIX."_blocks SET block_pos = '$prw' WHERE block_pos = '$its' && block_align = '$align'");
			$up1 = @mysql_query ("UPDATE ".DB_PEREFIX."_blocks SET block_pos = '$its' WHERE block_pos = '$its + 1000' && block_align = '$align'");
			if ($up0 && $up && $up1) site_message ("Блок перемещен");
			else site_error ("Ошибка при перемещении блока");
		}
		else site_error ("Невозможно двигать вверх");
	}
	else site_error ("Ошибка БД или нет такой записи");
}
if ($_GET['mod'] == "m_down" && isset($_GET['id'])) {
	$block = @mysql_fetch_array(mysql_query ("SELECT * FROM ".DB_PEREFIX."_blocks WHERE block_id = '$id'"));
	if ($block) {
		$its = $block['block_pos'];
		$next = $block['block_pos'] + 1;
		$align = $block['block_align'];
		if (@mysql_num_rows(mysql_query("SELECT * FROM ".DB_PEREFIX."_blocks WHERE block_pos = '$next' && block_align = '$align'")) == 1) {
			$up0 = @mysql_query ("UPDATE ".DB_PEREFIX."_blocks SET block_pos = '$its + 1000' WHERE block_pos = '$next' && block_align = '$align'");
			$up = @mysql_query ("UPDATE ".DB_PEREFIX."_blocks SET block_pos = '$next' WHERE block_pos = '$its' && block_align = '$align'");
			$up1 = @mysql_query ("UPDATE ".DB_PEREFIX."_blocks SET block_pos = '$its' WHERE block_pos = '$its + 1000' && block_align = '$align'");
			if ($up0 && $up && $up1) site_message ("Блок перемещен");
			else site_error ("Ошибка при перемещении блока");
		}
		else site_error ("Невозможно двигать вниз");
	}
	else site_error ("Ошибка БД или нет такой записи");
}
if ($_GET['mod'] == "hide" && isset($_GET['id'])) {
	$hide_block = @mysql_query ("UPDATE ".DB_PEREFIX."_blocks SET block_visible = 'hide' WHERE block_id = '$id'");
	if ($hide_block) site_message ("Блок спрятан");
}
if ($_GET['mod'] == "visible" && isset($_GET['id'])) {
	$hide_block = @mysql_query ("UPDATE ".DB_PEREFIX."_blocks SET block_visible = 'visible' WHERE block_id = '$id'");
	if ($hide_block) site_message ("Блок активизирован");
}
if ($_GET['save'] == "true") {
	$name = $_POST['name'];
	$header = $_POST['header'];
	$pos = $_POST['pos'];
	$group = $_POST['group'];
	$visible = $_POST['visible'];
	$file = $_POST['file'];
	$html = $_POST['html'];
	$align = $_POST['align'];
	
	$string = "";
	if (isset($_POST['modules_all'])) $string = "all";
	else {
		if (isset($_POST['start_page'])) $string = "start,";
		$get_modules = mysql_query ("SELECT module_name FROM ".DB_PEREFIX."_modules");
		while (list($mname) = mysql_fetch_row ($get_modules)) {
			if (isset($_POST['module_'.$mname])) $string .= $mname.",";
		}
	}
	if ($string == "") $string = "all";
	
	$gnum = @mysql_query ("SELECT * FROM ".DB_PEREFIX."_blocks WHERE block_pos = '$pos' AND block_align = '$align'");
	if ($name != "" && $pos != "" && $header != "" && mysql_num_rows ($gnum) == 0) {
		$insblock = @mysql_query ("INSERT INTO ".DB_PEREFIX."_blocks VALUES (0, '$name', '$header', '$html', '$file', '$pos', '$group', '$align', '$visible', '$string')");
		if ($insblock) site_message ("Блок добавлен");
		else site_error ("Ошибка БД");
	}
	else site_error ("Не заполнено поле или запись с таким порядковым номером уже существует<br><a href='javascript:history.back();'><b>Назад</b></a>");
}
if ($_GET['save'] == "edit_save") {
	$tid = $_POST['the_id'];
	$name = $_POST['name'];
	$header = $_POST['header'];
	$pos = $_POST['pos'];
	$group = $_POST['group'];
	$visible = $_POST['visible'];
	$file = $_POST['file'];
	$html = $_POST['html'];
	$align = $_POST['align'];
	
	$string = "";
	if (isset($_POST['modules_all'])) $string = "all";
	else {
		if (isset($_POST['start_page'])) $string = "start_page,";
		$get_modules = mysql_query ("SELECT module_name FROM ".DB_PEREFIX."_modules");
		while (list($mname) = mysql_fetch_row ($get_modules)) {
			if (isset($_POST['module_'.$mname])) $string .= $mname.",";
		}
	}
	if ($string == "") $string = "all";
	
	if ($name != "" && $pos != "" && $header != "" && $tid != "") {
		$updblock = @mysql_query ("UPDATE ".DB_PEREFIX."_blocks SET block_name = '$name', block_header = '$header', block_body = '$html', block_file = '$file', block_pos = '$pos', block_group = '$group', block_align = '$align', block_visible = '$visible', block_pages = '$string' WHERE block_id = '$tid'");
		if ($updblock) site_message ("Блок сохранен");
		else site_error ("Ошибка БД");
	}
	else site_error ("Не заполнено поле или запись с таким порядковым номером уже существует<br><a href='javascript:history.back();'><b>Назад</b></a>");
}
if ($_GET['mod'] == "align" && isset($_GET['id'])) {
	$select_b = @mysql_query ("SELECT * FROM ".DB_PEREFIX."_blocks WHERE block_id = '$id'");
	if ($select_b) {
		$bl = mysql_fetch_array ($select_b);
		if ($bl['block_align'] == "right") $align = "left";
		if ($bl['block_align'] == "left") $align = "right"; 
		$change = @mysql_query ("UPDATE ".DB_PEREFIX."_blocks SET block_align = '$align' WHERE block_id = '$id'");
		if ($change) site_message ("Блок перемещен");
		else site_error ("Ошибка БД");
	}
	else site_error ("Ошибка БД или нет такой записи");
}
if (!isset($_GET['act'])) {
	print '<ul id="top_nav"><li class="sel"><a href="/admin/">Панель администратора</a></li><li>Управление блоками</li></ul>';
	
	simple_table ("[ <a href='/admin/?do=blocks&act=add'>добавить блок</a> ]");
	print "\n<script>document.title='Управление блоками - ".$SITE['site_name']."';</script>";
	$gblock = @mysql_query ("SELECT * FROM ".DB_PEREFIX."_blocks ORDER BY $order");
	if ($gblock) {
		$block_tr = "";
		$color = "";
		while ($block = mysql_fetch_array ($gblock)) {
			if ($block['block_visible'] == "visible") $target = "Видим";
			elseif  ($block['block_visible'] == "hide") $target = "Невидим";
			if ($block['block_group'] == "all") $target = "Все";
			elseif ($block['block_group'] == "register") $target = "Зарегист.";
			if ($block['block_align'] == "left") $align = "Лево &nbsp;<a href='/admin/?do=blocks&mod=align&id=".$block['block_id']."'><img border=0 src='images/m_right.gif' alt='Направо'></a>";
			if ($block['block_align'] == "right") $align = "Право <a href='/admin/?do=blocks&mod=align&id=".$block['block_id']."'><img border=0 src='images/m_left.gif' alt='Налево'></a>";
			if ($block['block_group'] == "all") $group = "Все";
			if ($block['block_group'] == "register") $group = "Зарегистр.";
			if ($block['block_visible'] == "visible") $visible = "[ <a href='/admin/?do=blocks&mod=hide&id=".$block['block_id']."'>спрятать</a> ]";
			if ($block['block_visible'] == "hide") $visible = "[ <a href='/admin/?do=blocks&mod=visible&id=".$block['block_id']."'>показать</a> ]";
			if ($block['block_visible'] == "visible") $status = "<img src='images/work_on.gif' border=0 align=absmiddle title='Блок активен'> ";
			if ($block['block_visible'] == "hide") $status = "<img src='images/work_off.gif' border=0 align=absmiddle title='Блок неактивен'> ";
			$opt = "";
			if (@mysql_num_rows (mysql_query("SELECT * FROM ".DB_PEREFIX."_blocks WHERE block_align = '".$block['block_align']."' AND block_pos = '".($block['block_pos'] - 1)."'")) == 1) {
				$opt .= "<a href='/admin/?do=blocks&mod=m_up&id=".$block['block_id']."'><img src='images/m_up.gif' border=0 alt='Поднять вверх'></a> ";
			}
			if (@mysql_num_rows (mysql_query("SELECT * FROM ".DB_PEREFIX."_blocks WHERE block_align = '".$block['block_align']."' AND block_pos = '".($block['block_pos'] + 1)."'")) == 1) {
				$opt .= "<a href='/admin/?do=blocks&mod=m_down&id=".$block['block_id']."'><img src='images/m_down.gif' border=0 alt='Спустить вниз'></a>";
			}
			if ($block['block_visible'] == "hide") $color = _DARK_TR_;
			else $color = "";
			$block_tr .= "\n<tr bgcolor='$color'><td class=ad_tr>$status".$block['block_header']."</a></td><td class=ad_tr>$group</td><td class=ad_tr><center>$align</td><td class=ad_tr>$visible</td><td class=ad_tr><center>".$block['block_pos']." $opt</td><td class=ad_tr><center><a href='/admin/?do=blocks&act=edit&id=".$block['block_id']."'><img src='images/edit.gif' border=0 alt='Редактировать'></a><a href='javascript:delete_(\"/admin/?do=blocks&delete=true&id=".$block['block_id']."\");'><img src='images/cut.gif' border=0 alt='Удалить'></a></td></tr>";
		}
		$block_table = "\n<table class=body_table width='100%' cellspacing='0' cellpadding='3'>
		<tr><td class=top_header_name ><center>Название</td>".
		"<td class=top_header_name><center>Группа</td>".
		"<td class=top_header_name><center><a href='/admin/?do=blocks&order=block_align'>Положение</a></td>".
		"<td class=top_header_name><center>Статус</td>".
		"<td class=top_header_name><center><a href='/admin/?do=blocks&order=block_pos'>Позиция</a></td>".
		"<td class=top_header_name><center>Опции</td></tr>$block_tr
		\n</table><br><script>function delete_ (url_) {
		if (window.confirm('Вы действительно хотите удалить блок?') == true) document.location.href = url_;
		}</script>";
		past_table ("Управление блоками", $block_table);
	}
	else site_error ("Ошибка БД");
}
if ($_GET['act'] == "add") {
	print '<ul id="top_nav"><li class="sel"><a href="/admin/">Панель администратора</a></li><li><a href="/admin/?do=blocks">Управление блоками</a></li><li>Добавление нового блока</li></ul>';
	
	$position = @mysql_num_rows (mysql_query ("SELECT block_id FROM ".DB_PEREFIX."_blocks"));
	print "\n<script>document.title='Добавление блока - ".$SITE['site_name']."';</script>";
	add_block ("do=blocks&act=add&save=true", "", $_POST['name'], $_POST['header'], "include/blocks/", $_POST['html'], 'all', 'visible', $position, 'left', '');
	come_back ("управлению блоками", "/admin/?do=blocks");
}
if ($_GET['act'] == "edit" && isset($_GET['id'])) {
	print '<ul id="top_nav"><li class="sel"><a href="/admin/">Панель администратора</a></li><li><a href="/admin/?do=blocks">Управление блоками</a></li><li>Изменение блока</li></ul>';
	
	simple_table ("[ <a href='/admin/?do=blocks&act=add'>добавить блок</a> ]");
	print "\n<script>document.title='Исправление блока - ".$SITE['site_name']."';</script>";
	$select = @mysql_query ("SELECT * FROM ".DB_PEREFIX."_blocks WHERE block_id = '$id'");
	if ($select) {
		$block = mysql_fetch_array ($select);
		add_block ("do=blocks&save=edit_save", $id, $block['block_name'], $block['block_header'], $block['block_file'], $block['block_body'], $block['block_group'], $block['block_visible'], $block['block_pos'], $block['block_align'], $block['block_pages']);
	}
	else site_error ("Ошибка БД или нет такой записи");	
	come_back ("управлению блоками", "/admin/?do=blocks");
}

come_back ("панели администратора", "/admin/");

function add_block ($act, $id, $name, $title, $file, $html, $group, $visible, $pos, $align, $pages) {
	if ($group == "all") { $sel1 = "selected"; $sel2 = ""; }
	if ($group == "register") { $sel1 = ""; $sel2 = "selected"; }
	if ($visible == "visible") { $sel_1 = "selected"; $sel_2 = ""; }
	if ($visible == "hide") { $sel_1 = ""; $sel_2 = "selected"; }
	if ($align == "left") { $sel__1 = "selected"; $sel__2 = ""; }
	if ($align == "right") { $sel__1 = ""; $sel__2 = "selected"; }
	
	if ($pages == "all") $all = "checked";
	
	$pages_arr = array ();
	$pages = explode (",", $pages);
	foreach ($pages as $page) { if ($page != "") $pages_arr[$page] = 1; }
	
	if (isset($pages_arr["start_page"])) $start = "checked";
	
	$all_pages = "\n\t\t<div style=\"display:inline;float:left; width:220px;\"><input type=\"checkbox\" name=\"modules_all\" value=\"1\" $all /> все</div>
			<div style=\"display:inline;float:left; width:220px;\"><input type=\"checkbox\" name=\"start_page\" value=\"1\" $start /> главная</div>";
	$get_modules = mysql_query ("SELECT module_name, module_header FROM ".DB_PEREFIX."_modules");
	while (list($mname, $mheader) = mysql_fetch_row ($get_modules)) {
		(isset($pages_arr[$mname])) ? $slc = "checked" : $slc = "";
		$all_pages .= "\n\t\t<div style=\"display:inline;float:left; width:220px;\"><input type=\"checkbox\" name=\"module_$mname\" value=\"1\" $slc /> $mheader</div>";
	}
	
	
	$form = "\n\n<form style=\"margin:0px\" action=\"/admin/?$act\" method=\"post\" name=\"record\">
<input type=\"hidden\" name=\"the_id\" value=\"$id\">
<table class=\"main_text\" width=\"100%\" cellspacing=\"0\" cellpadding=\"3\">
	<tr>
		<td width=\"25%\">Название:</td>
		<td><input type=\"text\" name=\"name\" style=\"width:200px\" class=\"form\" value=\"$name\"> <a href=\"javascript:void(0)\" onmouseover=\"return overlib('Название должно содержать только латинские буквы.', BELOW, RIGHT);\" onmouseout=\"return nd();\">?</a></td>
	</tr>
	<tr>
		<td>Заголовок:</td>
		<td><input type=\"text\" name=\"header\" style=\"width:200px\" class=\"form\" value=\"$title\"></td>
	</tr>
	<tr>
		<td>Главный файл:</td>
		<td><input type=\"text\" name=\"file\" style=\"width:200px\" class=\"form\" value=\"$file\"> <a href=\"javascript:void(0)\" onmouseover=\"return overlib('Если вы не используете файл, то данное поле необходимо оставить пустым.', BELOW, RIGHT);\" onmouseout=\"return nd();\">?</a></td>
	</tr>
	<tr>
		<td>Позиция:</td>
		<td><input type=\"text\" name=\"pos\" style=\"width:80px\" class=\"form\" value=\"$pos\"> <a href='javascript:void(0)' onmouseover=\"return overlib('Данное поле заполняется и изменяется автоматически.', BELOW, RIGHT);\" onmouseout=\"return nd();\">?</a></td>
	</tr>
	<tr>
		<td valign=\"top\" width=\"25%\">HTML - код:</td>
		<td>
			<textarea class=\"form\" name=\"html\" style=\"width:400px\" rows=\"13\">$html</textarea><br>
			[ <a href='javascript:void(0);' onclick='javascript:document.record.html.rows=document.record.html.rows+10'>увеличить</a> ]
			[ <a href='javascript:void(0);' onclick='javascript:document.record.html.rows=document.record.html.rows-10'>уменьшить</a> ]
		</td>
	</tr>
	<tr>
		<td>Группа:</td>
		<td><select name=\"group\" class=\"form\"><option value=\"all\" $sel1>Все</option><option value=\"register\" $sel2>Зарегистрированные</option></select></td>
	</tr>
	<tr>
		<td>Видим.:</td>
		<td><select name=\"visible\" class=\"form\"><option value=\"visible\" $sel_1>Видим</option><option value=\"hide\" $sel_2>Скрыт</option></select></td>
	</tr>
	<tr>
		<td>Сторона:</td>
		<td><select name=\"align\" class=\"form\"><option value=\"left\" $sel__1>Левая</option><option value=\"right\" $sel__2>Правая</option></select></td>
	</tr>
	<tr>
		<td valign=\"top\">Страницы (модули):</td>
		<td>$all_pages</td>
	</tr>
	<tr>
		<td colspan=\"2\"><span class=\"important_button\"><input style=\"width:240px\" type=\"submit\" name=\"post\" value=\"Сохранить\" class=\"button\"></span> <input onclick=\"javascript:window.open('upload.php', '', 'width=500 height=300 scrollbars');\" type=\"button\" value=\"Загрузить что-нибудь\" class=\"button\"></td>
	</tr>
</table>
</form>";
	past_table ("Добавление/Изменение блока", $form);
}

?>
